<template>
  <!-- 增加修改 -->
  <a-drawer width="50%" :label-col="4" :wrapper-col="14" :visible="open" @close="onClose">
    <a-divider orientation="left">
      <b>{{ formTitle }}</b>
    </a-divider>
    <a-form-model ref="form" :model="form" :rules="rules" :layout="'horizontal'">
      <a-row :gutter="24">
        <a-col
          :span="12">
          <a-form-model-item label="入库单编号" prop="receiptNo">
            <a-input v-model="form.receiptNo" placeholder="系统生成" disabled/>
          </a-form-model-item>
        </a-col>
        <!-- 这里是下拉，数据源:生产指令单 orderList -->
        <a-col :span="12">
          <a-form-model-item label="生产指令单号" prop="productionOrderNo">
            <a-tree-select
              v-model="form.productionOrderNo"
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="productionOrderList"
              placeholder="请选择"
              :replaceFields="replaceFields"
              tree-default-expand-all
              @select="selectProductionOrderId"
            >
            </a-tree-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-model-item label="外部批次号" prop="externalBatchNo">
            <a-input v-model="form.externalBatchNo" placeholder="请输入"/>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="批次号" prop="batchNo">
            <a-input v-model="form.batchNo" placeholder="请输入" disabled/>
          </a-form-model-item>
        </a-col>
      </a-row>
      <!--      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-model-item label="登记人" prop="createBy">
            &lt;!&ndash; <a-input v-model="form.testQuantity" placeholder="请输入 *无*"/> &ndash;&gt;
            <a-tree-select
              v-model="form.createBy"
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="opeUsers"
              placeholder="请选择  *无*"
              :replaceFields="{ children: 'children', title: 'nickName', key: 'id', value: 'id' }"
              tree-default-expand-all
            >
            </a-tree-select>
          </a-form-model-item>
        </a-col>
      </a-row>-->
      <a-row :gutter="24">
        <a-col
          :span="12">
          <!-- externalBatchNumber -->
          <a-form-model-item label="零件名称" prop="partName" disabled>
            <a-tree-select
              v-model="form.partName"
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="processedTreeData"
              placeholder="请选择"
              :replaceFields="{
                children: 'children', title: 'title', key: 'key', value: 'value'
              }"
              tree-default-expand-all
              @select="selectPartName"
            >
            </a-tree-select>
            <!-- <a-input v-model="form.partName" placeholder="请输入" disabled/> -->
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="零件图号" prop="partDrawingNo" disabled>
            <a-input v-model="form.partDrawingNo" placeholder="请输入" disabled/>
          </a-form-model-item>
        </a-col>

      </a-row >
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-model-item label="零件简称" prop="partAbbreviation">
            <a-input v-model="form.partAbbreviation" placeholder="请输入 *指令单中没有该字段*" disabled/>
          </a-form-model-item>
        </a-col>

        <a-col :span="12">
          <a-form-model-item label="入库总数量" prop="totalQuantity">
            <a-input v-model="form.totalQuantity" placeholder="" disabled/>
          </a-form-model-item>
        </a-col>
      </a-row>

      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-model-item label="正式件数量" prop="formalQuantity">
            <a-input v-model="form.formalQuantity" placeholder="请输入" disabled/>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="试刀件数量" prop="testQuantity">
            <a-input v-model="form.testQuantity" placeholder="请输入 *无*" disabled/>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-model-item label="合格品数量" prop="qualifiedQuantity">
            <a-input v-model="form.qualifiedQuantity" placeholder="请输入" disabled/>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="不合格品数量" prop="unqualifiedQuantity	">
            <a-input v-model="form.unqualifiedQuantity	" placeholder="" disabled/>
          </a-form-model-item>
        </a-col>

      </a-row>

      <!--      <a-row :gutter="24">
        <a-col
          :span="12">
          <a-form-model-item label="登记日期" prop="createTime">
            <a-input v-model="form.createTime" placeholder="请输入 *无*" />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="登记人" prop="createBy">
            &lt;!&ndash; <a-input v-model="form.testQuantity" placeholder="请输入 *无*"/> &ndash;&gt;
            <a-tree-select
              v-model="form.createBy"
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="opeUsers"
              placeholder="请选择  *无*"
              :replaceFields="{ children: 'children', title: 'nickName', key: 'id', value: 'id' }"
              tree-default-expand-all
            >
            </a-tree-select>
          </a-form-model-item>
        </a-col>
      </a-row>-->

      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-model-item label="正式件仓库" prop="formalWarehouse">
            <a-input v-model="form.formalWarehouse" placeholder="请输入" />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="试刀件仓库" prop="testWarehouse">
            <a-input v-model="form.testWarehouse" placeholder="请输入" />
          </a-form-model-item>
        </a-col>
      </a-row>

      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-model-item label="WMS仓库" prop="productionBatchNo">
            <a-input v-model="form.productionBatchNo" placeholder="请输入 *无*" disabled/>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="层位" prop="productionBatchNo">
            <a-input v-model="form.productionBatchNo" placeholder="请输入 *无*" disabled />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col
          :span="24">
          <a-form-model-item label="备注" prop="remark">
            <a-input type="textarea" v-model="form.remark" placeholder="请输入" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-divider />
      <!-- 交付节点 -->
      <a-row :gutter="24" class="action-bar">
        <a-space>
          <!-- <span>出库明细</span> -->
          <a-button type="primary" class="editable-add-btn" @click="undelete">
            撤回删除
          </a-button>
        </a-space>
      </a-row>

      <a-row :gutter="24">
        <a-table bordered :data-source="form.warehouseReceiptItems" :columns="orderNodeListColumns" size="small" :pagination="false">
          <!-- 序号列插槽 -->
          <template slot="indexSlot" slot-scope="text, record, index">
            {{ index + 1 }}
          </template>

          <template slot="testPiece" slot-scope="text, record">
            <a-input :value="text == 0||text=='否'? '否': '是'" @change="e=>handleChange(e.target.value, record, 'testPiece')" disabled/>
          </template>

          <template slot="internalNumber" slot-scope="text, record">
            <a-input :value="text" @change="e=>handleChange(e.target.value, record, 'internalNumber')" disabled/>
          </template>

          <template slot="partNumber" slot-scope="text, record">
            <a-input :value="text" @change="e=>handleChange(e.target.value, record, 'partNumber')"/>
          </template>

          <template slot="castingNumber" slot-scope="text, record">
            <a-input :value="text" @change="e=>handleChange(e.target.value, record, 'castingNumber')" disabled/>
          </template>

          <template slot="partName" slot-scope="text, record">
            <a-input :value="text" @change="e=>handleChange(e.target.value, record, 'partName')" disabled/>
          </template>

          <!-- :show-time="{ defaultValue: dayjs('00:00:00', 'HH:mm:ss') }" -->
          <template slot="action" slot-scope="text, record">
            <a href="javascript:;" @click="handleDelete(record)" >删除</a>
          </template>
        </a-table>

      </a-row>

      <div class="bottom-control">
        <a-space>
          <a-button type="primary" :loading="submitLoading" @click="submitForm">
            保存
          </a-button>
          <a-button type="dashed" @click="cancel">
            取消
          </a-button>
        </a-space>
      </div>
    </a-form-model>
  </a-drawer>
</template>

<script>

import { getUser } from '@/api/system/user'
import { list as orderList } from '@/api/production/order'
import { add, getById, update } from '@/api/materials/productReceipt'
import dayjs from 'dayjs'
import customParseFormat from 'dayjs/plugin/customParseFormat'
import { warehouseReceiptItems } from '@/api/baseData/warehouseReceiptItems'
import { inventoryItem } from '@/api/baseData/inventory'

export default {
  name: 'CreateForm',
  props: {
    // projectId: {
    //   type: Object,
    //   required: true,
    //   defaulted: () => {}
    // }
  },
  components: {
  },
  data () {
    dayjs.extend(customParseFormat)
    return {
      submitLoading: false,
      replaceFields: { children: 'children', title: 'orderNo', key: 'orderNo', value: 'orderNo' },
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      formTitle: '',
      // 表单参数
      form: {
        shipmentNumber: undefined,
        productionOrderNo: undefined,
        partName: undefined,
        externalBatchNo: undefined,
        incomingQuantity: undefined,
        partDrawingNo: undefined,
        partAbbreviation: undefined,
        qualifiedQuantity: undefined,
        testQuantity: undefined,
        customerName: undefined,
        formalQuantity: undefined,
        formalWarehouse: undefined,
        testWarehouse: undefined,
        remark: undefined,

        warehouseReceiptItems: [],
        projectId: undefined,
        type: 1 // 出库
      },
      open: false,
      rules: {

        partName: [
          { required: true, message: '零件名称不能为空', trigger: 'blur' }
        ]
      },
      orderNodeListColumns: [
      {
        title: '序号',
        key: 'index',
        scopedSlots: { customRender: 'indexSlot' }, // 索引从0开始，+1后从1显示
        width: 80,
        align: 'center'
      },
        {
          title: '是否是试刀件',
          dataIndex: 'testPiece',
          ellipsis: true,
          scopedSlots: { customRender: 'testPiece' },
          width: 80
        },
        {
          title: '实际零件内部编号',
          dataIndex: 'internalNumber',
          scopedSlots: { customRender: 'internalNumber' },
          ellipsis: true,
          width: 80
        },
        {
          title: '零件号',
          dataIndex: 'partNumber',
          scopedSlots: { customRender: 'partNumber' },
          ellipsis: true,
          width: 80
        },
        {
          title: '铸件号',
          dataIndex: 'castingNumber',
          scopedSlots: { customRender: 'castingNumber' },
          ellipsis: true,
          width: 80
        },
        {
          title: '是否合格',
          dataIndex: 'qualified',
          scopedSlots: { customRender: 'qualified' },
          ellipsis: true,
          width: 80
        },
        {
          title: '不合格品原因',
          dataIndex: 'unQualifiedReason',
          scopedSlots: { customRender: 'unQualifiedReason' },
          ellipsis: true,
          width: 80
        },
        {
          title: '零件名称',
          dataIndex: 'partName',
          scopedSlots: { customRender: 'partName' },
          ellipsis: true,
          width: 80
        },
        {
          title: '内部批次号',
          dataIndex: 'internalNumber',
          scopedSlots: { customRender: 'internalNumber' },
          ellipsis: true,
          width: 80
        },
        {
          title: '操作',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
          width: 50
        }

      ],
      partPlanIncomingList: [],
      inventoryItemList: [],
      nametestPieceEnum: [
        { label: '是', value: 1 },
        { label: '否', value: 0 }
      ],
      productionOrderList: [],
      deleteList: [],
      opeUsers: [],
      projectId: ''
    }
  },
  filters: {
  },
  created () {
    this.init()
  },
  computed: {
    // 处理后的数据，拼接 name 和 code
    processedTreeData () {
      const processData = (data) => {
        return this.inventoryItemList.map(item => ({
          title: `(${item.inventoryCode}|${item.inventoryName})`, // 拼接两个字段
          value: item.inventoryName,
          key: item.id,
          children: item.children ? processData(item.children) : undefined
        }))
      }
      return processData(this.rawTreeData)
    }
  },
  watch: {
    'form.warehouseReceiptItems': {
      handler (newItems) {
        console.log('数组内对象属性变化', newItems)
        var testNum = 0
        var num = 0
        newItems.forEach((element, index) => {
          if (element.nametestPiece === 1) {
            element.internalNumber = 'S' + ++testNum
          } else {
            element.internalNumber = 'Z' + ++num
          }
        })
        this.form.formalQuantity = num
        this.form.testQuantity = testNum
        this.form.totalQuantity = (num + testNum)
      },
      deep: true // 深度监听
    }
  },
  methods: {
    dayjs, // 将 dayjs 作为方法暴露给模板
    init () {
      this.getOrderList()
      this.getOperator()
    },
    getOperator () {
      getUser().then(res => {
        this.opeUsers = res.data
      })
    },
    // 加载生产指令单数据
    getOrderList () {
      orderList().then(res => {
        this.productionOrderList = res.data
        console.info(res, 'getOrderList', this.productionOrderList)
      })
    },
    // 选择生产指令单
    selectProductionOrderId (value) {
      this.form.productionOrderNo = value
      const order = this.productionOrderList.filter(item => item.orderNo === this.form.productionOrderNo)[0]
      this.form = {
        ...this.form,
        batchNo: order.externalBatchNo,
        partName: order.partName,
        partDrawingNo: order.partDrawingNo,
        partAbbreviation: order.partAbbreviation

      }
      this.getwarehouseReceiptItems({
        partDrawingNo: this.form.partDrawingNo,

        status: 1
      })
    },
    // 加载毛坯出库明细
    getwarehouseReceiptItems (query) {
      warehouseReceiptItems(query).then(res => {
        console.info(res, 'partDrawingNo')
        this.form.warehouseReceiptItems = res.data
      })
    },
    // 删除
    handleDelete (record) {
      this.form.warehouseReceiptItems = this.form.warehouseReceiptItems.filter(item => item.id !== record.id)
      this.deleteList.push(record)
    },
    // 设置table form 值
    handleChange (e, info, ee) {
      console.info(e, info, ee)
      info[ee] = e
    },
    // 撤回删除
    undelete () {
      if (this.deleteList.length > 0) {
        console.info(this.deleteList)
        const del = this.deleteList.pop()
        console.info(del)
        this.form.warehouseReceiptItems.push(del)
      }
    },
    // 选择外部批次号
    selectExternalBatchNumber (selectedKeys, info) {
      console.info((this.partPlanIncomingList.filter(it => it.id === selectedKeys)[0]))
      this.form.partDrawingNo = (this.partPlanIncomingList.filter(it => it.id === selectedKeys)[0]).partDrawingNo
      this.form.batchNo = (this.partPlanIncomingList.filter(it => it.id === selectedKeys)[0]).batchNumber
    },
    // 存货档案
    getinventoryItem () {
      inventoryItem().then(res => {
        this.inventoryItemList = res.rows
      })
    },

    // 选择零件名称
    selectPartName (selectedKeys, info) {
      console.log('selected', selectedKeys, info, this.inventoryItemList.filter(it => it.inventoryName === selectedKeys)[0])
      this.form.partAbbreviation = (this.inventoryItemList.filter(it => it.inventoryName === selectedKeys)[0]).shortName
      this.form.unitOfMeasurement = (this.inventoryItemList.filter(it => it.inventoryName === selectedKeys)[0]).unitOfMeasurement
      this.form.wmsName = (this.inventoryItemList.filter(it => it.inventoryName === selectedKeys)[0]).wmsName
      this.form.wmsStorey = (this.inventoryItemList.filter(it => it.inventoryName === selectedKeys)[0]).wmsStorey
    },
    onClose () {
      this.open = false
    },
    // 取消按钮
    cancel () {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset () {
      this.form = {
        shipmentNumber: undefined,
        productionOrderNo: undefined,
        partName: undefined,
        externalBatchNo: undefined,
        incomingQuantity: undefined,
        partDrawingNo: undefined,
        partAbbreviation: undefined,
        qualifiedQuantity: undefined,
        testQuantity: undefined,
        customerName: undefined,
        formalQuantity: undefined,
        formalWarehouse: undefined,
        testWarehouse: undefined,
        remark: undefined,

        warehouseReceiptItems: [],
        projectId: this.selectProjectId,
        type: 1 // 出库
      }
    },
     /** 新增按钮操作 */
    handleAdd (selectProjectId) {
      console.info('handleAdd', selectProjectId)
      if (!selectProjectId) {
        this.$message.error(
                '请先选择项目',
                3
              )
        return
      }
      this.reset()
      this.$emit('select-tree')
      this.open = true
      this.formTitle = '产成品入库单'
      this.selectProjectId = selectProjectId
      this.form = {
        shipmentNumber: undefined,
        productionOrderNo: undefined,
        partName: undefined,
        externalBatchNo: undefined,
        incomingQuantity: undefined,
        partDrawingNo: undefined,
        partAbbreviation: undefined,
        qualifiedQuantity: undefined,
        testQuantity: undefined,
        customerName: undefined,
        formalQuantity: undefined,
        formalWarehouse: undefined,
        testWarehouse: undefined,
        remark: undefined,

        warehouseReceiptItems: [],
        projectId: selectProjectId,
        type: 1 // 出库
      }

      this.init()
    },
    /** 修改按钮操作 */
    handleUpdate (row, ids) {
      this.reset()
      this.$emit('select-tree')

      getById(row.id).then(res => {
        this.form = res.data
        this.open = true
        this.formTitle = '修改产成品入库单'
      })
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.submitLoading = true
          if (this.form.id !== undefined) {
            update(this.form).then(response => {
              this.$message.success(
                '修改成功',
                3
              )
              this.open = false
              this.$emit('ok')
            }).finally(() => {
              this.submitLoading = false
            })
          } else {
            add(this.form).then(response => {
              this.$message.success(
                '新增成功',
                3
              )
              this.open = false
              this.$emit('ok')
            }).finally(() => {
              this.submitLoading = false
            })
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>
